package org.gary.equipment.action;

import static lengreen.util.constant.Constant.DateFomaterString.YYYY_MM_DD_HH_MM_SS;
import static org.gary.core.util.Utils.*;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import org.apache.struts2.interceptor.SessionAware;
import org.gary.base.model.Category;
import org.gary.base.model.Image;
import org.gary.base.service.CategoryService;
import org.gary.base.service.ImageService;
import org.gary.base.service.XxxImageService;
import org.gary.core.service.InitService;
import org.gary.core.util.Util;
import org.gary.core.util.Utils;
import org.gary.equipment.model.Equipment;
import org.gary.equipment.service.EquipmentService;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.opensymphony.xwork2.ActionSupport;

/**
 * 设备action
 * 
 * @author lengreen
 * 
 */
@Component
@Scope("prototype")
public class EquipmentAction extends ActionSupport implements
		ServletResponseAware, ServletRequestAware, SessionAware {
	private static final long serialVersionUID = 5224924145319298545L;

	private HttpServletResponse response;
	private HttpServletRequest request;
	private Map<String, Object> session;
	private InitService initService;

	@Resource
	public void setInitService(InitService initService) {
		this.initService = initService;
	}

	private EquipmentService equipmentService;
	private CategoryService categoryService;
	private XxxImageService xxxImageService;
	private ImageService imageService;
	/** 记录单个产品信息 */
	private Equipment equipment;
	/** 记录产品列表信息 */
	private List<Equipment> equipmentList;
	/** 记录当前页 */
	private int start;
	/** 记录分页最大记录条数 */
	private int limit;
	/** 记录设备名称信息 */
	private String equipmentName;
	/** 开始时间 */
	private String fromDate;
	/** 结束时间 */
	private String toDate;
	/** 类别 */
	private String category;
	
	/** 记录产品每页最大条数 */
	private final int MAXEQUIPMENT = 12;

	/** 用于规定上传文件的大小 **/
	private static final int BUFFER_SIZE = 200 * 1024;
	private File[] equipmentImage;
	/** 用String数组来封装多个上传文件名 **/
	private String[] equipmentImageFileName;
	/** 用String数组来封装多个上传文件类型 **/
	private String[] equipmentImageContentType;
	/** 删除模式 */
	private String mode;
	/** 删除谁的图片 */
	private String who;
	/** 是否可见 */
	private String visible;
	/** 语言 */
	private String lang;

	/**
	 * 添加一个设备
	 * @throws Exception
	 */
	public void add() throws Exception {
		String msg = "";
		if (equipment != null) {
			Set<Image> images = Utils.handleImagesUpload(equipmentImage,
					equipmentImageFileName, "EquipmentImage", BUFFER_SIZE);
			Category c = getCategoryService().loadCategoryByName(category,
					equipment.getLang());
			equipment.setImages(images);
			equipment.setCategory(c);
			equipmentService.save(equipment);
			msg = "{'success':'true'}";
		} else {
			msg = "{'success':'false'}";
		}
		response.setCharacterEncoding("utf-8");
		response.getWriter().write(msg);
	}

	/**
	 * 列出所有设备
	 * 
	 * @throws Exception
	 */
	public void list() throws Exception {
		start = parseIndex(start, limit);
		Map<String, Object> where = new HashMap<String, Object>();
		where.put(" entity.visible = ", new Boolean(visible));
		setEquipmentList(equipmentService.list(Equipment.class, start, limit,
				where, new Object[] { " entity.id desc " }));

		JsonConfig config = makeDateFormateJsonConfig(YYYY_MM_DD_HH_MM_SS);
		config.setExcludes(new String[] { "images", "notes", "visible" });
		JSONArray equipmentListJsonArray = JSONArray.fromObject(equipmentList, config);
		JSONObject equipmentJsonObject = new JSONObject();
		equipmentJsonObject.put("equipmentTotal", equipmentService
				.selectTotalCount(null));
		equipmentJsonObject.put("equipmentList", equipmentListJsonArray);
		response.setCharacterEncoding("utf-8");
		response.getWriter().write(equipmentJsonObject.toString());
	}

	/**
	 * 搜索设备
	 * 
	 * @throws Exception
	 */
	public void search() throws Exception {
		start = parseIndex(start, limit);
		Map<String, Object> where = new HashMap<String, Object>();
		where.put(" entity.visible = ", new Boolean(visible));
		setCategory(new String(category.getBytes("iso8859-1"), "utf-8"));

		System.out.println("equipmentName-->" + equipmentName);
		System.out.println("fromDate-->" + fromDate);
		System.out.println("toDate-->" + toDate);
		System.out.println("category-->" + category);

		if (!"".equals(equipmentName.trim())) {
			where.put(" entity.name like ", equipmentName);
		}
		if (!"".equals(fromDate.trim())) {
			if ("".equals(toDate.trim())) {
				where.put(" entity.createDate between ", fromDate
						+ " 00:00:00' and '"
						+ Utils.getFormatDate(new Date(), YYYY_MM_DD_HH_MM_SS));
			} else {
				where.put(" entity.createDate between ", fromDate
						+ " 00:00:00' and '" + toDate + " 23:59:59");
			}
		}
		if (!"".equals(category.trim())) {
			where.put(" entity.category.name = ", "'" + category + "'");
		}
		if (!"".equals(lang.trim())) {
			where.put(" entity.lang = ", lang);
		}

		setEquipmentList(equipmentService.list(Equipment.class, start, limit,
				where, new Object[] { " entity.id desc " }));

		JsonConfig config = makeDateFormateJsonConfig(YYYY_MM_DD_HH_MM_SS);
		config.setExcludes(new String[] { "images", "notes", "visible" });
		JSONArray equipmentListJsonArray = JSONArray.fromObject(equipmentList, config);
		JSONObject equipmentJsonObject = new JSONObject();
		equipmentJsonObject.put("equipmentTotal", equipmentService
				.selectTotalCount(null));
		equipmentJsonObject.put("equipmentList", equipmentListJsonArray);
		System.out.println("equipmentJsonObject-->"
				+ equipmentJsonObject.toString());
		response.setCharacterEncoding("utf-8");
		response.getWriter().write(equipmentJsonObject.toString());
	}

	/**
	 * 加载一个设备
	 * @throws IOException
	 */
	public void load() throws IOException {
		Equipment p = equipmentService.load(Equipment.class, equipment.getId());
		JsonConfig config = makeDateFormateJsonConfig(YYYY_MM_DD_HH_MM_SS);
		config.setExcludes(new String[] { "category.parent",
				"category.children", "images" });
		JSONObject productJsonObject = JSONObject.fromObject(p, config);
		response.setCharacterEncoding("utf-8");
		response.getWriter().write(productJsonObject.toString());
	}

	/**
	 * 加载关联图片
	 * 
	 * @throws IOException
	 */
	public void loadImages() throws IOException {
		JsonConfig config = makeDateFormateJsonConfig(YYYY_MM_DD_HH_MM_SS);
		config.setExcludes(new String[] { "createDate", "id", "visible" });
		JSONArray imagesJsonArray = JSONArray.fromObject(equipmentService
				.loadImages(equipment.getId()), config);
		JSONObject imagesJsonObject = new JSONObject();
		imagesJsonObject.put("images", imagesJsonArray);
		response.setCharacterEncoding("utf-8");
		response.getWriter().write(imagesJsonObject.toString());
	}

	/**
	 * 更新一个设备
	 * 
	 * @throws IOException
	 */
	public void update() throws IOException {
		String msg = "";
		if (equipment != null) {
			Set<Image> images = handleImagesUpload(equipmentImage,
					equipmentImageFileName, "EquipmentImage", BUFFER_SIZE);
			if (images == null) {
				images = new HashSet<Image>();
			}
			for (Image i : equipmentService.loadImages(equipment.getId())) {
				images.add(i);
			}
			equipment.setImages(images);

			Category c = categoryService.loadCategoryByName(category, equipment
					.getLang());
			equipment.setCategory(c);
			equipmentService.update(equipment);
			msg = "{'success':'true'}";
		} else {
			msg = "{'success':'false'}";
		}
		response.setCharacterEncoding("utf-8");
		response.getWriter().write(msg);
	}

	/**
	 * 删除一个设备
	 * 
	 * @throws IOException
	 */
	public void delete() throws IOException {
		try {
			String result = "";
			if ("delete".equals(getMode())) {
				Object[] imageIds = getXxxImageService().deleteByXxxId(
						getWho(), equipment.getId());
				if (imageIds.length > 0) {
					getImageService().delete(Image.class, imageIds);
				}
				equipmentService.delete(equipment);
				result = "{'result':'delete'}";
			} else if ("update".equals(getMode())) {
				equipmentService.update(Equipment.class,
						new Object[] { equipment.getId() }, false);
				result = "{'result':'update'}";
			} else {
				result = "{'result':'none'}";
			}
			response.setCharacterEncoding("utf-8");
			response.getWriter().write(result);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 回收一个设备
	 * 
	 * @throws IOException
	 */
	public void recover() throws IOException {
		try {
			String result = "";
			if (equipment != null) {
				Equipment e = equipmentService.load(Equipment.class, equipment
						.getId());
				if (e.getCategory().isVisible()) {
					equipmentService.update(Equipment.class,
							new Object[] { equipment.getId() }, true);
					result = "{'success':'true', 'msg':'recover'}";
				} else {
					result = "{'success':'false', 'msg':'categoryUnvisible'}";
				}
			} else {
				result = "{'success':'false', 'msg':'null'}";
			}
			response.setCharacterEncoding("utf-8");
			response.getWriter().write(result);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	// -----------------------------------------------------------------------------------

	public String equipmentList() {
		initService.initAll(session);
		
		List<Equipment> banner=equipmentService.getEquipmentList(10,0,session.get("WW_TRANS_I18N_LOCALE"),-1);
		request.setAttribute("banner", banner);
		
		String equipmentType = request.getParameter("equipmentType");
		List<Equipment> equipmentList = null;
		int equipmentCurrentPage;
		String equipmentPage = request.getParameter("productPage");
		if (equipmentPage != null) {
			equipmentCurrentPage = Integer.parseInt(equipmentPage);
		} else {
			equipmentCurrentPage = 0;
		}
		// 得到分页bean
		Util u = new Util("equipment", MAXEQUIPMENT, session.get("WW_TRANS_I18N_LOCALE"));
		if (equipmentType == null) {
			equipmentList = equipmentService.getEquipmentList(MAXEQUIPMENT, equipmentCurrentPage, session
					.get("WW_TRANS_I18N_LOCALE"), -1);
		} else {
			if(Integer.parseInt(equipmentType)!=0){
				if (!equipmentService.getParentId(Integer.parseInt(equipmentType))) {
					equipmentList=equipmentService.list(Equipment.class, MAXEQUIPMENT, equipmentCurrentPage, session
							.get("WW_TRANS_I18N_LOCALE"), equipmentService
							.getId(Integer.parseInt(equipmentType)));
				} else {
					equipmentList = equipmentService.getEquipmentList(MAXEQUIPMENT, equipmentCurrentPage, session
							.get("WW_TRANS_I18N_LOCALE"), Integer
							.parseInt(equipmentType));
				}
				u = new Util("equipment", MAXEQUIPMENT, Integer.parseInt(equipmentType),session.get("WW_TRANS_I18N_LOCALE"));
			}else{
				equipmentList = equipmentService.getEquipmentList(MAXEQUIPMENT, equipmentCurrentPage, session
						.get("WW_TRANS_I18N_LOCALE"), -1);
			}
		}
		// 设置当前页面
		u.setYe(equipmentCurrentPage);

		/** 把分页request */
		request.setAttribute("fenye", u);
		request.setAttribute("equipmentList", equipmentList);
		return SUCCESS;
	}

	public String equipmentView() {
		initService.initAll(session);
		
		List<Equipment> banner=equipmentService.getEquipmentList(10,0,session.get("WW_TRANS_I18N_LOCALE"),-1);
		request.setAttribute("banner", banner);
		
		String equipmentId = request.getParameter("equipmentId");
		if (equipmentId != null) {
			Equipment equipmentbean = equipmentService.load(Equipment.class,
					Integer.parseInt(equipmentId), session
							.get("WW_TRANS_I18N_LOCALE"));
			request.setAttribute("equipmentbean", equipmentbean);
			return SUCCESS;
		} else {
			session.put("error", "设备显示失败，参数错误！");
			return ERROR;
		}
	}

	public String searchEquipment() {
		initService.initAll(session);
		
		List<Equipment> banner=equipmentService.getEquipmentList(10,0,session.get("WW_TRANS_I18N_LOCALE"),-1);
		request.setAttribute("banner", banner);
		
		Map<String, Object> where = new HashMap<String, Object>();
		where.put(" entity.visible = ", new Boolean(true));
		String equipmentFun = request.getParameter("equipmentFun");
		if (equipmentFun != null) {
			String equipmentWhat = request.getParameter("equipmentWhat").trim();
			if ("date".equals(equipmentFun)) {
				where.put("entity.createDate like ", equipmentWhat);
			} else if ("type".equals(equipmentFun)) {
				Category cate = categoryService.load(Category.class,
						equipmentWhat, session.get("WW_TRANS_I18N_LOCALE"));
				where.put("entity.category.id = ", cate.getId());
			} else if ("model".equals(equipmentFun)) {
				where.put("entity.model like ", equipmentWhat);
			} else if ("name".equals(equipmentFun)) {
				where.put("entity.name like ", equipmentWhat);
			}
			where.put("entity.lang = ", session.get("WW_TRANS_I18N_LOCALE")
					.toString());
			List<Equipment> equipmentList = equipmentService.list(
					Equipment.class, 0, 9, where,
					new Object[] { " entity.id desc " });
			request.setAttribute("equipmentList", equipmentList);
			return SUCCESS;
		} else {
			session.put("error", "设备显示失败，参数错误！");
			return ERROR;
		}
	}

	@Override
	public void setServletResponse(HttpServletResponse response) {
		this.response = response;
	}

	@Resource
	public void setEquipmentService(EquipmentService equipmentService) {
		this.equipmentService = equipmentService;
	}

	public EquipmentService getEquipmentService() {
		return equipmentService;
	}

	public Equipment getEquipment() {
		return equipment;
	}

	public void setEquipment(Equipment equipment) {
		this.equipment = equipment;
	}

	public List<Equipment> getEquipmentList() {
		return equipmentList;
	}

	public void setEquipmentList(List<Equipment> equipmentList) {
		this.equipmentList = equipmentList;
	}

	public int getStart() {
		return start;
	}

	public void setStart(int start) {
		this.start = start;
	}

	public int getLimit() {
		return limit;
	}

	public void setLimit(int limit) {
		this.limit = limit;
	}

	public String getEquipmentName() {
		return equipmentName;
	}

	public void setEquipmentName(String equipmentName) {
		this.equipmentName = equipmentName;
	}

	public String getFromDate() {
		return fromDate;
	}

	public void setFromDate(String fromDate) {
		this.fromDate = fromDate;
	}

	public String getToDate() {
		return toDate;
	}

	public void setToDate(String toDate) {
		this.toDate = toDate;
	}

	public String getCategory() {
		return category;
	}

	public void setCategory(String category) {
		this.category = category;
	}

	@Resource
	public void setCategoryService(CategoryService categoryService) {
		this.categoryService = categoryService;
	}

	public CategoryService getCategoryService() {
		return categoryService;
	}

	public void setEquipmentImage(File[] equipmentImage) {
		this.equipmentImage = equipmentImage;
	}

	public File[] getEquipmentImage() {
		return equipmentImage;
	}

	public void setEquipmentImageFileName(String[] equipmentImageFileName) {
		this.equipmentImageFileName = equipmentImageFileName;
	}

	public String[] getEquipmentImageFileName() {
		return equipmentImageFileName;
	}

	public void setEquipmentImageContentType(String[] equipmentImageContentType) {
		this.equipmentImageContentType = equipmentImageContentType;
	}

	public String[] getEquipmentImageContentType() {
		return equipmentImageContentType;
	}

	public void setMode(String mode) {
		this.mode = mode;
	}

	public String getMode() {
		return mode;
	}

	public void setWho(String who) {
		this.who = who;
	}

	public String getWho() {
		return who;
	}

	public void setVisible(String visible) {
		this.visible = visible;
	}

	public String getVisible() {
		return visible;
	}

	public void setLang(String lang) {
		this.lang = lang;
	}

	public String getLang() {
		return lang;
	}

	@Resource
	public void setXxxImageService(XxxImageService xxxImageService) {
		this.xxxImageService = xxxImageService;
	}

	public XxxImageService getXxxImageService() {
		return xxxImageService;
	}

	@Resource
	public void setImageService(ImageService imageService) {
		this.imageService = imageService;
	}

	public ImageService getImageService() {
		return imageService;
	}

	@Override
	public void setServletRequest(HttpServletRequest request) {
		this.request = request;
	}

	@Override
	public void setSession(Map<String, Object> session) {
		this.session = session;
	}
}
